package com.jwx.mycar.utils;

import com.baidu.aip.imageclassify.AipImageClassify;
import com.jwx.mycar.common.Constants;
import com.jwx.mycar.entity.po.Recognition;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 百度AI图像识别
 */
public class AIImage {
	public static final String APP_ID = Constants.APP_ID;
	public static final String API_KEY = Constants.API_KEY;
	public static final String SECRET_KEY = Constants.SECRET_KEY;

	public static AipImageClassify client;

	/**
	 * 识别图片
	 */
	public static List<Recognition> classify(String picPath) {
		initClient();
		JSONObject res = client.carDetect(FileUtils.getAbsolutePath(picPath), null);
		JSONArray ja = (JSONArray)res.get("result");
		List<Recognition> ret = new ArrayList<Recognition>();
		for (int i = 0; i < ja.length(); i++) {
			JSONObject item = ja.getJSONObject(i);
			Recognition re = new Recognition();
			re.setScore(item.getDouble("score"));
			re.setName(item.getString("name"));
			ret.add(re);
		}

		return ret;
	}

	/**
	 * 识别图片
	 */
	public static List<Recognition> classifyByURL(String picPath) {
		initClient();
		JSONObject res = client.carDetect(picPath, null);
		JSONArray ja = (JSONArray)res.get("result");
		List<Recognition> ret = new ArrayList<Recognition>();
		for (int i = 0; i < ja.length(); i++) {
			JSONObject item = ja.getJSONObject(i);
			Recognition re = new Recognition();
			re.setScore(item.getDouble("score"));
			re.setName(item.getString("name"));
			ret.add(re);
		}

		return ret;
	}

	private static void initClient() {
		if (client == null) {
			client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
			client.setConnectionTimeoutInMillis(2000);
			client.setSocketTimeoutInMillis(60000);
		}
	}
}
